<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="用户昵称" prop="userId">
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择用户"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.name"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="批次编码" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变动来源类型" prop="changeSourceType">
        <el-select v-model="queryParams.changeSourceType" multiple placeholder="请选择变动来源类型" clearable style="width: 240px">
          <el-option
            v-for="dict in sourceTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['points:points:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['points:points:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pointsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户昵称" align="center" prop="userId">
        <template #default="scope">
          {{ getUserNameById(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="积分变动数量" align="center" prop="pointsChange" />
      <el-table-column label="变动前积分余额" align="center" prop="pointsBefore" />
      <el-table-column label="变动后积分余额" align="center" prop="pointsAfter" />
      <el-table-column label="变动来源类型" align="center" prop="changeSourceType">
        <template #default="scope">
          <span>{{ formatSourceType(scope.row.changeSourceType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次编码" align="center" prop="batchCode" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['points:points:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script setup name="Points">
import { listPoints, getPoints, delPoints, addPoints, updatePoints } from "@/api/points/points";
import { listUser } from "@/api/system/user"; 

const { proxy } = getCurrentInstance();

const pointsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userOptions = ref([]); // 添加用户选项变量

// 变动来源类型选项
const sourceTypeOptions = [
  { value: "1", label: "答题奖励" },
  { value: "2", label: "发帖奖励" },
  { value: "3", label: "帖子获赞" },
  { value: "4", label: "帖子被收藏" },
  { value: "5", label: "发评论奖励" },
  { value: "6", label: "评论获赞" },
  { value: "7", label: "商品兑换" },
  { value: "8", label: "系统调整" },
  { value: "9", label: "活动奖励" },
  { value: "10", label: "签到奖励" }
];

// 格式化变动来源类型
function formatSourceType(type) {
  const sourceType = sourceTypeOptions.find(item => item.value == type);
  return sourceType ? sourceType.label : type;
}

// 获取用户列表
function getUserList() {
  listUser().then(response => {
    if (response.code === 200 && response.rows) {
      userOptions.value = response.rows.map(item => ({
        id: item.userId,
        name: item.nickName || item.userName || `用户${item.userId}`
      }));
    } else {
      userOptions.value = [];
      proxy.$modal.msgError("获取用户列表失败");
    }
  }).catch(() => {
    userOptions.value = [];
    proxy.$modal.msgError("获取用户列表失败");
  });
}

// 添加获取用户昵称的方法
function getUserNameById(id) {
  if (!id) return '';
  const user = userOptions.value.find(item => item.id == id);
  return user ? user.name : `用户${id}`;
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    changeSourceType: [], 
    batchCode: null,
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询积分变动记录列表 */
function getList() {
  loading.value = true;
  listPoints(queryParams.value).then(response => {
    pointsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    recordCode: null,
    userId: null,
    pointsChange: null,
    pointsBefore: null,
    pointsAfter: null,
    changeSourceType: null,
    batchCode: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    deletedFlag: null
  };
  proxy.resetForm("pointsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.changeSourceType = []; 
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pointsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePoints(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPoints(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除积分变动记录编号为"' + _ids + '"的数据项？').then(function() {
    return delPoints(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('points/points/export', {
    ...queryParams.value
  }, `points_${new Date().getTime()}.xlsx`)
}

getUserList(); 
getList();
</script>
